package com.ymk.cmd;

import cn.hutool.core.util.IdUtil;
import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.service.WxService;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.work.WorkShareBO;
import com.ymk.core.code.cmd.WorkCmdCode;
import com.ymk.core.code.resp.RespCode;
import com.ymk.core.constants.WxConstants;
import com.ymk.service.IWorkShareService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class WorkShareCmd extends ACmd {

    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        WorkShareBO reqData = super.getData(sign, WorkShareBO.class);


        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("userId", reqData.getUserId())
                .addParam("page", reqData.getPage())
                .addParam("workId", reqData.getWorkId())
                .setReturnStruct(sign.getReturnStruct());
        WorkShareBO respData = workShareService.get(paramsBuilder.build());
        if (!Objects.isNull(respData)) {
            WorkShareBO workShareBO = new WorkShareBO();
            workShareBO.setFilePath(respData.getFilePath());
            respSign.setSource(super.getSource(workShareBO));
        } else {
            // 文件存储路径
            String path = WxConstants.WX_File_PATH+ IdUtil.simpleUUID()+".jpg";
            // 生产分享的小程序码并上传至云托管
            String filePath  =  wxServce.uploadFile(reqData,path);
            WorkShareBO workShareBO = new WorkShareBO();
            workShareBO.setFilePath(filePath);
            respSign.setSource(super.getSource(workShareBO));
            reqData.setFilePath(filePath);
            this.setCreatedData(sign,reqData);
            workShareService.post(reqData);
        }


        return respSign;
    }

    public CmdSign verify(HttpServletRequest request, CmdSign sign) throws Exception {
        WorkShareBO reqData = super.getData(sign, WorkShareBO.class);

        if (StringUtils.isBlank(reqData.getPage())) {
            throw new MallException(RespCode.CODE_ERROR, "分享页不能为空");
        }
        if (StringUtils.isBlank(reqData.getUserId())) {
            throw new MallException(RespCode.CODE_ERROR, "分享人Id不能为空");
        }

        return null;
    }

    @Override
    public String getCmdCode() {
        return WorkCmdCode.WORK_SHARE;
    }

    @Override
    public boolean anon(CmdSign sign) {
        return true;
    }

    @Autowired
    private WxService wxServce;
    @Autowired
    private IWorkShareService workShareService;
}